﻿//=============================================================
// Copyright (C) 2011 iSun Studio 软件工作室
// 作 者：江怀玉
// 日 期：2011-10-11
// 描 述: 用于生成数据结果的JSON数据格式
// URL parameter:
//        entity:当前实体对象名称(不一定是表名)
//        codition:过滤数据条件
//        pageindex:当前页
//        pagesize:页记录数
//        type:JSON的数据类型，有时候用于List.aspx使用，有时用于生成对应的JS Obecjt Entity!
//        order:排序
// 版 本：1.00
// 修改历史纪录
// 版 本  修改时间      修改人            修改内容
// 1.00   2011/10/11   江怀玉    
// 1.01   2011/11/21   江怀玉            增加获取数据权限功能
// 1.02   2011/11/23   江怀玉            增加获取自定义查询条件功能
// 1.05   2012/02/29   江怀玉            增加自定义部门查询条件功能
// 1.06   2012/04/11   江怀玉            增加缓存数据
//=============================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iSun.Common;
using iSun.BLL;
using iSun.BLL.Base;
using iSun.Model;
using System.Text.RegularExpressions;
using System.Text;


using iSun.Web.UI.Controls;
using iSun.BLL.Base;

namespace iSun.WebApp.AjaxData
{
    public partial class JSONList : BasePage
    {

        string strEntity = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            strEntity = this.GetStringFromQueryString("entity", "E_Menu");            //对应的实体
            string strCondition = this.GetStringFromQueryString("condition", "");            //系统特定条件
            string strCustomCondition = this.GetStringFromQueryString("customCondition", "");//自定义条件
            int iPageIndex = this.GetIntFromQueryString("pageindex", 0);                     //第N页？
            int iPageSize = this.GetIntFromQueryString("pagesize", 0);                       //页记录数？
            string IsOnlyTotal = this.GetStringFromQueryString("onlyTotal","false");         //是否只回传记录总数?
            string IsDesc = this.GetStringFromQueryString("desc", "false");                  //Yes or No
            string IsSetCache = this.GetStringFromQueryString("setcache", "false");
            string IsRefreshCache = this.GetStringFromQueryString("IsRefreshCache", "false");
            // strCondition = Server.UrlDecode(strCondition);
            // strCustomCondition = Server.UrlDecode(strCustomCondition);
            // 系统数据权限
            strCondition = strCondition == "" ? getRoleCondition() : strCondition + (getRoleCondition() == "" ? "" : " and "+getRoleCondition());
            strCondition = strCondition == "" ? strCustomCondition : strCondition + (strCustomCondition == "" ? "" : " and " + strCustomCondition);
            
            
            string strType = this.GetStringFromQueryString("type", "");
            string strOrder = this.GetStringFromQueryString("order", "");
            strEntity= strEntity.Split(',')[0];
       
            //记录数
            int totalrecord = GetTotal(strEntity,strCondition);

            if (IsOnlyTotal == "true")
            {
                Response.Write("[{\"total\":" + totalrecord.ToString() + "}]");
                return;
            }

            if (IsSetCache == "true")
            {
                if (IsRefreshCache == "false")
                {
                    SetCache(strEntity, strCondition, totalrecord, iPageSize, strOrder);
                }
                else
                {
                    RefreshCache(strEntity, strCondition, totalrecord, iPageSize, strOrder);
                }
                return;
            }
            //if(iSun.Common.
            if ((GetCondtionCache(strEntity)==strCondition)&&!string.IsNullOrEmpty(GetDataCache(strEntity, iPageIndex)))
            {
                HttpContext.Current.Response.Write(GetDataCache(strEntity, iPageIndex));
                return;
            }

            IList<BaseEntity> list;
            list = GetData(strEntity, iPageIndex, iPageSize, strOrder, strCondition);

            if (list==null)
            {
                HttpContext.Current.Response.Write("{\"total\":" + totalrecord.ToString() + ",\"rows\":[]}");
                return;
            }
            //int totalrecord = bll.GetRowCount(strCondition);
            //string strFormat = "{\"total\":" + totalrecord.ToString() + ",\"rows\":[";
            
            //strFormat = strFormat + str + "]}";
            //strFormat = strFormat.Replace(new Regex("(^|[^\\\\])\\\"\\\\/Date\\((-?[0-9]+)\\)\\\\/\\\"","$1new Date($2)");
            if (strType =="1")
            {
                string str = list.ToJSON().Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("@@", " ");
                HttpContext.Current.Response.Write("[" + str.Replace("null","").Replace("[A]","&") + "]");
            }
            else
            {
                HttpContext.Current.Response.Write(GetListJson(list,totalrecord));
            }
            //iSunContext.Current.Context.Response.Write("["+str+"]");
        }
        public string GetListJson(IList<BaseEntity> list, int totalrecord)
        {
            string strFormat = "{\"total\":" + totalrecord.ToString() + ",\"rows\":[";
            string str = list.ToJSON().Replace("\n", " ").Replace("\r", " ").Replace("null", "").Replace("[BR]", " ").Replace("@@@@", " ").Replace("@@", " ");
            strFormat = strFormat + str + "]}";
            return strFormat;
        }
        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="iPageIndex"></param>
        /// <param name="iPageSize"></param>
        /// <param name="strOrder"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public IList<BaseEntity> GetData(string strEntity, int iPageIndex, int iPageSize, string strOrder, string strCondition)
        {
            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            _bll.entity = entity;
            BaseBussnies bll = _bll;// new BaseBussnies<BaseEntity>(entity);
            bll.PageIndex = iPageIndex;
            bll.PageSize = iPageSize == 0 ? 25 : iPageSize;
            bll.Order = strOrder;
            bll.Desc = "Yes";
            if (bll.PageIndex == 0)
            {
                return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysByCondition("1=1") : bll.GetEntitysByCondition(strCondition);
            }
            else
            {
                return string.IsNullOrEmpty(strCondition) ? bll.GetEntitysSplitPage("1=1") : bll.GetEntitysSplitPage(strCondition);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strCondition"></param>
        /// <returns></returns>
        public int GetTotal(string strEntity, string strCondition)
        {
            BaseEntity entity = iSun.Common.Reflection.CreateEntitysInstance(strEntity) as BaseEntity;
            BaseBussnies<BaseEntity> bll = new BaseBussnies<BaseEntity>(entity);
            return bll.GetRowCount(strCondition);
        }
        /// <summary>
        /// 获取角色数据权限信息
        /// </summary>
        /// <returns></returns>
        public string getRoleCondition()
        {
            if (this.User == null)
            {
                Session["User"] = BUser.CreateInstance().GetDatUserByUName("Admin");
            }
            return this.User.GetDataCondition(this.FunctionID, strEntity);
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="condition">页</param>
        public void SetCache(string entity, string condition, int total, int pagesize, string strOrder)
        {
            iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_Condition", condition,60*20);

            int page = total / pagesize+1;
            page = page > 20 ? 20 : page;
            for (int i = 1; i < page + 1; i++)
            {
                IList<BaseEntity> list = GetData(entity, i, pagesize, strOrder, condition);
                iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_" + i, GetListJson(list, total), 60 * 20);
            }
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <param name="entity">实体类</param>
        /// <param name="pageindex">页</param>
        /// <returns></returns>
        public string GetDataCache(string entity, int pageindex)
        {
            return iSun.Common.WebCache.Get(entity + "_" + this.UserName + "_" + pageindex) as string;
        }

        public string GetCondtionCache(string entity)
        {
            return iSun.Common.WebCache.Get(entity + "_" + this.UserName + "_Condition") as string;
        }

        public void RefreshCache(string entity, string condition, int total, int pagesize, string strOrder)
        {
            int page = total / pagesize + 1;
            page = page > 20 ? 20 : page;
            #region 去掉缓存
            iSun.Common.WebCache.Remove(entity + "_" + this.UserName + "_Condition");
            for(int i=1;i<page+1 ;i++)
            {
                iSun.Common.WebCache.Remove(entity + "_" + this.UserName + "_" + i);
            }
            #endregion
            iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_Condition", condition, 60 * 20);

            for (int i = 1; i < page + 1; i++)
            {
                IList<BaseEntity> list = GetData(entity, i, pagesize, strOrder, condition);
                iSun.Common.WebCache.Insert(entity + "_" + this.UserName + "_" + i, GetListJson(list, total), 60 * 20);
            }
        }
    }
}
